#include "co_rtmp_writer.hpp"
#include "co_chunk_stream.hpp"
#include "co_rtmp_session.hpp"
#include "flv_pub.hpp"
#include "logger.hpp"
#include <stdio.h>

namespace cpp_streamer
{
    RtmpWriter::RtmpWriter(CoRtmpSession* session, Logger* logger) : session_(session)
        , logger_(logger)
    {
    }

    RtmpWriter::~RtmpWriter()
    {

    }
    int RtmpWriter::WritePacket(Media_Packet_Ptr pkt_ptr) {
        uint16_t csid;
        uint8_t  type_id;

        if (pkt_ptr->av_type_ == MEDIA_VIDEO_TYPE) {
            csid = 6;
            type_id = RTMP_MEDIA_PACKET_VIDEO;
        }
        else if (pkt_ptr->av_type_ == MEDIA_AUDIO_TYPE) {
            csid = 4;
            type_id = RTMP_MEDIA_PACKET_AUDIO;
        }
        else if (pkt_ptr->av_type_ == MEDIA_METADATA_TYPE) {
            csid = 6;
            type_id = pkt_ptr->typeid_;
        }
        else {
            LogErrorf(logger_, "doesn't support av type:%d", (int)pkt_ptr->av_type_);
            return -1;
        }
        WriteDataByChunkStream(session_, csid,
            (uint32_t)pkt_ptr->dts_, type_id,
            pkt_ptr->streamid_, session_->GetChunkSize(),
            pkt_ptr->buffer_ptr_);
        return RTMP_OK;
    }

    std::string RtmpWriter::GetKey() {
        return session_->req_.key_;
    }

    std::string RtmpWriter::GetWriterId() {
        return session_->GetSessonKey();
    }

    void RtmpWriter::CloseWriter() {
        LogInfof(logger_, "rtmp writer closed");
    }

    bool RtmpWriter::IsInited() {
        return init_flag_;
    }

    void RtmpWriter::SetInitFlag(bool flag) {
        init_flag_ = flag;
    }
}
